<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <category @tree-node-click="changeNodeClick"></category>
        </el-col>
        <el-col :span="20">
          <el-form ref="form" label-width="80px" :model="searchDto" :inline="true">
            <el-form-item label="组名">
              <el-input
                v-model="searchDto.attrGroupName"
                size="small"
                placeholder="请输入组名"
                prefix-icon="el-icon-search"
              >
                <template #suffix>
                  <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="searchDto.description"
                size="small"
                placeholder="请输入描述信息"
                prefix-icon="el-icon-mobile-phone"
              >
                <template #suffix>
                  <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" size="small" @click="onSearch"
                >搜索</el-button
              >
              <el-button :icon="Refresh" size="small" @click="refresh">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row>
            <el-col :span="24">
              <el-button type="primary" plain :icon="Plus" size="small" @click="addAttrGroup"
                >新增属性分组</el-button
              >
              <el-button type="info" plain :icon="BottomRight" size="small">导入</el-button>
              <el-button type="warning" plain :icon="TopRight" size="small">导出</el-button>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-table v-loading="loading" :data="tableData" border style="width: 100%">
              <el-table-column prop="attrGroupName" label="组名" width="150" align="center" />
              <el-table-column prop="sort" label="排序" width="150" align="center" />
              <el-table-column prop="description" label="描述" width="150" align="center" />
              <el-table-column prop="icon" label="分组图标" width="150" align="center">
                <template #default="scope">
                  <el-icon :size="size" style="vertical-align: middle; margin-right: 8px">
                    <component :is="scope.row.icon" />
                  </el-icon>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="handleGetAttrGroupRelationPage(scope.row.attrGroupId)"
                  >
                    关联规格属性
                  </el-button>
                  <el-button size="small" type="warning" @click="handleEdit(scope.row.attrGroupId)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row.attrGroupId)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-pagination
              v-model:current-page="pageNo"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :size="size"
              :background="background"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              style="margin-top: 10px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-col>
      </el-row>

      <!-- 弹窗 -->
      <el-dialog v-model="dialogVisible" :title="Tips" width="500" @close="handleClose">
        <el-form
          ref="ruleFormRef"
          :model="attrGroup"
          label-width="auto"
          style="max-width: 600px"
          :rules="rules"
        >
          <el-form-item label="分组名称" prop="attrGroupName">
            <el-input v-model="attrGroup.attrGroupName" placeholder="请输入分类名称"></el-input>
          </el-form-item>
          <el-form-item label="分组图标" prop="icon">
            <SelectIcon
              v-model="attrGroup.icon"
              :size="20"
              :width="200"
              placeholder="请选择一个图标"
              :preview-size="32"
              :preview-margin-top="12"
            />
          </el-form-item>
          <el-form-item label="分组描述" prop="description">
            <el-input v-model="attrGroup.description"></el-input>
          </el-form-item>
          <el-form-item label="所属分类" prop="catId">
            <el-cascader
              v-model="attrGroup.catId"
              :options="options"
              :props="cascaderProps"
              clearable
              filterable
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitData"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 属性关联，这里采用el-drawer抽屉框组件，从上方抽屉弹出 -->
      <el-drawer
        v-model="drawer"
        :direction="direction"
        :show-close="true"
        :size="800"
        @close="drawerHandleClose"
      >
        <template #header>
          <el-form :model="searchSpecificationsDto" :inline="true" label-width="auto">
            <el-form-item label="规格属性名称" prop="attrGroupName">
              <el-input
                v-model="searchSpecificationsDto.attrName"
                placeholder="请输入分类名称"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button :icon="Search" type="primary" size="small" @click="onSpecificationSearch"
                >搜索</el-button
              >
              <el-button :icon="Refresh" size="small" @click="refrehSpecificationSearch"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </template>
        <template #default>
          <el-row style="margin-bottom: 20px">
            <el-button type="primary" size="small" @click="handleAddAttrBtn">添加关联</el-button>
            <el-button
              size="small"
              type="warning"
              :disabled="dataArray.length <= 0"
              @click="handleBatchDeleteSpecification"
              >批量删除</el-button
            >
          </el-row>
          <el-table
            :data="specTableData"
            border
            style="width: 100%"
            @selection-change="handleSpecSelect"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" prop="attrName" label="规格属性名称" width="180" />
            <el-table-column align="center" prop="valueSelect" label="可选值列表" width="180" />
            <el-table-column align="center" label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="danger"
                  @click="removeAttrGroupIdRelationBtn(scope.row.attrId)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template #footer>
          <el-pagination
            v-model:current-page="specPageNo"
            v-model:page-size="specPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :size="size"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSpecCount"
            @size-change="handleSpecSizeChange"
            @current-change="handleSpecCurrentChange"
          />
        </template>
      </el-drawer>

      <el-dialog
        v-model="attrDialogVisible"
        title="新增规格属性"
        width="600"
        @close="attrHandleClose"
      >
        <template #header>
          <el-form :model="attrSearchDto" label-width="auto" :inline="true">
            <el-form-item label="属性名称">
              <el-input
                v-model="attrSearchDto.attrName"
                size="small"
                placeholder="请输入属性名称"
                prefix-icon="el-icon-search"
              >
                <template #suffix>
                  <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :icon="Search"
                size="small"
                @click="onSearchAttrGroupRelation"
                >搜索</el-button
              >
              <el-button :icon="Refresh" size="small" @click="refreshAttrGroupRelation"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </template>

        <el-table
          :data="attrTableData"
          border
          style="width: 100%"
          @selection-change="handleAttrSelect"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" prop="attrName" label="属性名称" />
          <el-table-column align="center" prop="valueSelect" label="可选值列表" />
        </el-table>
        <el-pagination
          v-model:current-page="attrPageNo"
          v-model:page-size="attrPageSize"
          style="margin-top: 15px"
          :page-sizes="[10, 20, 50, 100]"
          :size="size"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalAttrCount"
          @size-change="handleAttrSizeChange"
          @current-change="handleAttrCurrentChange"
        />

        <template #footer>
          <div class="dialog-footer">
            <el-button size="small" @click="attrDialogVisible = false">取消</el-button>
            <el-button
              size="small"
              type="primary"
              :disabled="attrAttrGroupRelationDataArrays.length <= 0"
              @click="submitDataAttrGroupRelation"
            >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import SelectIcon from '@/components/common/select-icon.vue'
import category from '@/components/common/category.vue'
import { ref, reactive, onMounted } from 'vue'
import { categoryList } from '@/api/category'
import {
  getAttrGroupList,
  insertAttrGroup,
  updateAttrGroup,
  getAttrGroup,
  deleteAttrGroup,
  findPageAttrGroupId,
  batchRemoveAttrGroupRelation,
  findPageCanAttrRelationList,
  batchSaveAttrGroupRelation
} from '@/api/attrGroup'
import { Search, Refresh, Plus, BottomRight, TopRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const cascaderProps = {
  multiple: false, //是否可以多选，false:单选，true:多选
  checkStrictly: false, // false不允许选择任意级别,只能选择最后一级
  value: 'catId',
  label: 'name',
  children: 'children',
  emitPath: false //在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}
//分类多级列表
const options = ref([])
// 分页器当前的页码数
const pageNo = ref(1)
// 分页器每页显示多少条数据
const pageSize = ref(10)
//分页器大小
const size = ref('default')
const searchDto = ref({
  attrGroupName: '',
  description: '',
  catId: null
})
//加载状态
const loading = ref(false)
//列表数据
const tableData = ref([])
const totalCount = ref()
// 分页器背景颜色，是/否
const background = ref(true)
// 弹窗状态 默认不显示
const dialogVisible = ref(false)
const Tips = ref('')
//dialog表单数据
const attrGroup = ref({
  attrGroupId: null,
  attrGroupName: '',
  description: '',
  icon: null,
  catId: 0
})
const ruleFormRef = ref()
//对话框类型:作用用来提交数据时候，区分是修改还是添加
const dialogType = ref('')
/**
 * 表单验证规则
 */
const rules = reactive({
  attrGroupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
  logo: [{ required: true, message: '请选择上传的图标', trigger: 'blur' }],
  description: [{ required: true, message: '请输入分组描述', trigger: 'blur' }],
  catId: [{ required: true, message: '请选择所属分类', trigger: 'blur' }]
})
/**
 * 弹窗关闭
 */
const handleClose = () => {
  console.log('弹窗关闭')
  dialogType.value = ''
  Tips.value = ''
  //清空表单数据
  attrGroup.value = {}
}
/**
 * 分页器每页显示多少条数据发生改变
 */
const handleSizeChange = () => {
  console.log('每页可展示的条数发生改变', pageSize.value)
  attrGroupList()
}
/**
 * 分页器当前页码数发生改变
 */
const handleCurrentChange = () => {
  console.log('页码数发生改变', pageNo.value)
  attrGroupList()
}

const refresh = () => {
  searchDto.value.attrGroupName = ''
  searchDto.value.description = ''
}
const onSearch = () => {
  attrGroupList()
}

const changeNodeClick = data => {
  // console.log('父组件感知到子组件传递过来的数据')
  // console.log(data)
  // console.log(data.catId)
  if (data.catLevel === 3) {
    searchDto.value.catId = data.catId
    attrGroupList()
  }
}
/**
 * 组件加载完成,获取新增的时候的下拉选择框数据，并不是我们页面左侧的树形数据
 */
onMounted(() => {
  attrGroupList()
})
/**
 * 获取属性分组列表
 */
const attrGroupList = async () => {
  loading.value = true
  const { records, total } = await getAttrGroupList(pageNo.value, pageSize.value, searchDto.value)
  tableData.value = records
  totalCount.value = total
  loading.value = false
}
/**
 * 点击编辑按钮
 * @param attrGroupId
 */
const handleEdit = async attrGroupId => {
  dialogVisible.value = true
  dialogType.value = 'edit'
  Tips.value = '修改属性分组'
  //回显分类数据
  options.value = await categoryList()
  //先回显数据
  getAttrGroupInfo(attrGroupId)
}
/**
 * 新增属性分组按钮
 */
const addAttrGroup = async () => {
  dialogVisible.value = true
  dialogType.value = 'add'
  Tips.value = '新增属性分组'
  options.value = await categoryList()
}
/**
 * 点击删除按钮
 */
const handleDelete = attrGroupId => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 确定删除
      await deleteAttrGroup(attrGroupId)
      await attrGroupList()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

/**
 * 确定按钮提交数据
 *  */
const submitData = async () => {
  if (!ruleFormRef.value) return
  try {
    // 如果校验失败，这里会 throw
    await ruleFormRef.value.validate()
    // 校验通过
    // … 发接口、关闭弹窗之类的
    console.log('校验通过，开始提交')

    if (dialogType.value == 'add') {
      await saveAttrGroup()
    } else {
      await editAttrGroup()
    }
    dialogVisible.value = false
    //刷新页面列表
    await attrGroupList()
  } catch (err) {
    // 校验不通过或其它错误都会走到这
    console.warn('校验失败：', err)
    ElMessage.error('请检查表单必填项或格式')
  }
}

const saveAttrGroup = async () => {
  await insertAttrGroup(attrGroup.value)
  ElMessage({
    type: 'success',
    message: '添加成功'
  })
}
const editAttrGroup = async () => {
  await updateAttrGroup(attrGroup.value)
  ElMessage({
    type: 'success',
    message: '修改成功'
  })
}
/**
 * 更具id获取属性分组信息
 * @param attrGroupId
 */
const getAttrGroupInfo = async attrGroupId => {
  //注意这里catId会自动回显分组的值
  attrGroup.value = await getAttrGroup(attrGroupId)
}

// 抽屉框的显示和隐藏
const drawer = ref(false)
// 抽屉框的显示方向
const direction = ref('rtl')
const specPageNo = ref(1)
const specPageSize = ref(10)
const totalSpecCount = ref(0)
const searchSpecificationsDto = ref({
  // 规格参数名称
  attrName: '',
  // 分组id
  attrGroupId: null
})
//表格数据
const specTableData = ref([])
/**
 * 获取当前分组下的所有关联的规格参数属性分页列表
 * @param attrGroupId
 */
const handleGetAttrGroupRelationPage = attrGroupId => {
  drawer.value = true
  searchSpecificationsDto.value.attrGroupId = attrGroupId
  getSpecPageListTableData()
}
//搜索
const onSpecificationSearch = () => {
  getSpecPageListTableData()
}
//重置搜索
const refrehSpecificationSearch = () => {
  searchSpecificationsDto.value.attrName = ''
  getSpecPageListTableData()
}
const handleSpecSizeChange = () => {
  console.log('每页可展示的条数发生改变', specPageSize.value)
}
const handleSpecCurrentChange = () => {
  console.log('当前页码发生改变', specPageNo.value)
}
const drawerHandleClose = () => {
  console.log('抽屉框关闭了')
  searchSpecificationsDto.value.attrName = ''
  searchSpecificationsDto.value.attrGroupId = null
  drawer.value = false
}
/**
 * 获取当前分组下的所有关联的规格参数属性分页列表
 */
const getSpecPageListTableData = async () => {
  const { records, total } = await findPageAttrGroupId(
    specPageNo.value,
    specPageSize.value,
    searchSpecificationsDto.value
  )
  specTableData.value = records
  totalSpecCount.value = total
}
const dataArray = ref([])
//批量选择  @selection-change="handleSpecSelect" selectArrays有一个参数就是当前选中的数据行
const handleSpecSelect = selectArrays => {
  //获取当前分组的id
  const attrGroupId = searchSpecificationsDto.value.attrGroupId
  //组装批量删除的参数
  dataArray.value = selectArrays.map(({ attrId }) => ({
    attrId,
    attrGroupId: attrGroupId
  }))
  //获取到勾选的数据
  //console.log(selectArrays)
  //console.log(dataArray)
}

/**
 * 批量删除关联的规格参数属性
 */
const handleBatchDeleteSpecification = () => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 确定删除
      await batchRemoveAttrGroupRelation(dataArray.value)
      await getSpecPageListTableData()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}
/**
 * 单个删除关联的规格参数属性
 */
const removeAttrGroupIdRelationBtn = attrId => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      //组装参数
      const dataArray = [
        {
          attrId: attrId,
          attrGroupId: searchSpecificationsDto.value.attrGroupId
        }
      ]
      // 确定删除
      await batchRemoveAttrGroupRelation(dataArray)
      await getSpecPageListTableData()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}
// 弹窗显示
const attrDialogVisible = ref(false)
// 弹窗关闭
const attrHandleClose = () => {
  console.log('弹窗关闭了')
  attrDialogVisible.value = false
  attrSearchDto.value.attrName = ''
  attrSearchDto.value.attrGroupId = null
}

const attrSearchDto = ref({
  // 属性名称
  attrName: '',
  // 分组id
  attrGroupId: null
})
// 属性列表数据
const attrTableData = ref([])
const attrPageNo = ref(1)
const attrPageSize = ref(10)
const totalAttrCount = ref(0)
const handleAttrSizeChange = () => {
  getAttrPageListTableData()
}
const handleAttrCurrentChange = () => {
  getAttrPageListTableData()
}
/**
 * 添加关联的规格参数属性按钮
 */
const handleAddAttrBtn = () => {
  attrDialogVisible.value = true
  attrSearchDto.value.attrGroupId = searchSpecificationsDto.value.attrGroupId
  getAttrPageListTableData()
}
const onSearchAttrGroupRelation = () => {
  getAttrPageListTableData()
}
const refreshAttrGroupRelation = () => {
  attrSearchDto.value.attrName = ''
  getAttrPageListTableData()
}
/**
 * 获取当前分组下的所有可选的规格参数属性分页列表
 */
const getAttrPageListTableData = async () => {
  const { records, total } = await findPageCanAttrRelationList(
    specPageNo.value,
    specPageSize.value,
    attrSearchDto.value
  )
  attrTableData.value = records
  totalAttrCount.value = total
}
const attrAttrGroupRelationDataArrays = ref([])
/**
 * 选中的数据集合
 * @param selectArrays
 */
const handleAttrSelect = selectArrays => {
  //收集选中的数据的attrId
  attrAttrGroupRelationDataArrays.value = selectArrays.map(({ attrId }) => ({
    attrId,
    attrGroupId: searchSpecificationsDto.value.attrGroupId
  }))
  //console.log(selectArrays)
}
/**
 * 批量添加关联的规格参数属性
 */
const submitDataAttrGroupRelation = () => {
  insertAttrGroupRelation(attrAttrGroupRelationDataArrays.value)
}
const insertAttrGroupRelation = async dataArrays => {
  await batchSaveAttrGroupRelation(dataArrays)
  attrDialogVisible.value = false
  await getSpecPageListTableData()
  ElMessage({
    type: 'success',
    message: '添加成功'
  })
}
</script>

<style scoped></style>
